package com.zoroki.hmusic.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QiniuUtil {
    public static final String  accessKey = "u30bmE3iWod1c9hm16x25Zuf32fT1zOhIeFOVe4c";
    public static final String  secretKey = "yyCe9xfmkmlU_QqDlEAYKzIFBxIioBQb1MsFUojb";
    public static final String  bucket = "h-music2";

    public static String getUpToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        log.info("获取upToken:{}",upToken);
        return upToken;
    }


    public static void uploadFile(String filename,String folder,byte[] bytes) throws QiniuException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.regionCnEast2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = folder + filename;
        String upToken = getUpToken();
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet =
                    new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("key:{}",putRet.key);
            log.info("hash:{}",putRet.hash);
            log.info("文件上传成功:{}",filename);
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
    }

    public static void deleteFile(String filename){
        Configuration cfg = new Configuration(Region.regionCnEast2());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, filename);
            log.info("文件删除成功:{}",filename);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            log.error(String.valueOf(ex.code()));
            log.error(String.valueOf(ex.response.toString()));
        }
    }
}
